/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their name, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: PeerNode.java,v 1.13 2007/02/08 23:41:29 hamada Exp $
*/

package net.jxta.myjxta.util.objectmodel;

import net.jxta.myjxta.presence.PeerStatus;
import net.jxta.myjxta.util.Env;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.Peer;
import net.jxta.myjxta.util.Resources;

import javax.swing.*;

/**
 * @author james todd [gonzo at jxta dot org]
 * @version $Id: PeerNode.java,v 1.13 2007/02/08 23:41:29 hamada Exp $
 */

public class PeerNode
        extends JxtaNode {

    /**
     * The category used by this peer
     */
    public static final String CATEGORY_PEER = "peer";

    /**
     * The Peer object wrapped by this node
     */
    private Peer peer = null;

    /**
     * The time we heard from this peer
     */
    private long lastAccess = -1;

    /**
     * Is this peer present
     */
    private boolean isPresent = false;
    public static final String CONNECTION_ONGOING = "STATUS_REQUESTED";
    public static final String STATUS_PRESENCE = "STATUS_PRESENCE";
    public static final String STATUS_REACHABLE = "STATUS_REACHABLE";
    public static final String STATUS_REVERSE_DISCOVERED = "STATUS_REVERSE_DISCOVERED";
    private boolean m_showProcessingGraphic = false;
    Boolean m_lastDirectConnectionWasSucessful = null;

    //does the opposite Peer
    private Boolean m_reverseDiscovery = null;
    private PeerStatus presenceStatus = null;
    private int m_unreachableCounter = -1;

    // xxx: hack

    /**
     * Create a new PeerNode
     *
     * @param peer the peer wrapped by this node
     */
    public PeerNode(Peer peer) {
        this(peer, null); // xxx: group
    }

    /**
     * Create a new PeerNode
     *
     * @param peer   the peer wrapped by this node
     * @param parent the parent group
     */
    public PeerNode(Peer peer, Group parent) {
        super(null, peer.getId(), peer.getName(), CATEGORY_PEER);

        this.peer = peer;

        setParent(new GroupNode(parent));
    }

    /**
     * Return the peer associated with this  node
     *
     * @return the peer associated with this  node
     */
    public Peer getPeer() {
        return this.peer;
    }

    /**
     * Check whether this peer equals the given object.
     * This is true if o is an instance of PeerNode and
     * if the two Peer objects wrapped by PeerNode are equal
     *
     * @param o the object to which to compare
     * @return true if the peer groups represents by the
     *         two GroupNodes being compared are the same
     */
    public boolean equals(Object o) {
        return (o instanceof PeerNode &&
                this.peer.equals(((PeerNode) o).getPeer()));
    }

    /**
     * hash method must be over-ridden if equals() is over-ridden.
     * The Object api says that if two objects evaulate as equal using
     * the equals() method, then their hash codes must be equal.
     * <p/>
     * This hash method ensures that the hash codes reflect the
     * information evaluated by equals.
     *
     * @return hash code for this GroupNode.
     */
    public int hashCode() {
        return this.peer.hashCode();
    }

    public int compareTo(Object o) {
        return (o instanceof PeerNode ?
                equals(o) ? 0 : toString().compareToIgnoreCase(o.toString())
                : -1);
    }

    /**
     * Return the image to return for this
     * JxtaNode
     *
     * @param selected is the node currently selected
     * @param expanded is the node currently expanded
     * @param hasFocus has the node currently keyboard focus
     */
    public ImageIcon getImage(boolean selected, boolean expanded,
                              boolean hasFocus) {
        Resources res = Resources.getInstance();
        ImageIcon icon;

        if (isPresent) {
            icon = res.getIconResource("TreeTable.PeerPresent");
        } else {
            icon = res.getIconResource("TreeTable.PeerAbsent");
        }

        return icon;
    }

    public GroupNode getParent() {
        return (GroupNode) super.getParent();
    }

    /**
     * This method may be called if the node was already added to the tree
     * but was accessed. This implementation does nothing
     *
     * @return true if the status of the node changed, false otherwise
     */
    public boolean informAccessed() {
        long tmp = System.currentTimeMillis();
        boolean result = false;

        // first time we heard from this peer
        if (lastAccess == -1) {
            result = true;
        }
        // this peer was marked not present and has now changed status
        else if (tmp - lastAccess > 2 * 60 * 1000 * Env.PING_INTERVAL) {
            result = true;
        }

        lastAccess = tmp;
        isPresent = true;

        return result;
    }

    /**
     * Check whether the status of this node has changed.
     */
    public boolean checkStatus() {
        long tmp = System.currentTimeMillis();
        boolean result = false;

        // Have never heard from this peer
        if (lastAccess == -1) {
            result = false;
        }
        // if tmp - lastAccess is larger than 2 * 60 * 1000 * Env.PING_INTERVAL
        // this peer is now gone
        else if (tmp - lastAccess > 2 * 60 * 1000 * Env.PING_INTERVAL) {
            if (isPresent) {
                isPresent = false;
                result = true;
            }
        }

        return result;
    }

    public long getLastAccessTimestamp() {
        return lastAccess;
    }

    /**
     * @return true, false, null (null -> unknown)
     */
    public Boolean wasReachable() {
        return m_lastDirectConnectionWasSucessful;
    }

    /**
     * @return true, false, null (null -> unknown)
     */
    public Boolean getReverseDiscoveryState() {
        return m_reverseDiscovery;
    }


    public boolean isConnecting() {
        return m_showProcessingGraphic;
    }

    public PeerStatus getPresenceStatus() {
        return presenceStatus;
    }

    public void setInfo(String key, Object value, boolean informListeners) {
        if (key.equals(PeerNode.CONNECTION_ONGOING)) {
            m_showProcessingGraphic = value != null;

        } else if (key.equals(PeerNode.STATUS_REACHABLE)) {
            m_lastDirectConnectionWasSucessful = (Boolean) value;
            if (Boolean.TRUE.equals(m_lastDirectConnectionWasSucessful)) {
                informAccessed();
                m_unreachableCounter = 0;
            } else {
                m_unreachableCounter++;
            }
        } else if (key.equals(PeerNode.STATUS_PRESENCE)) {
            if (value != null) {
                presenceStatus = (PeerStatus) value;
                if ((presenceStatus.getState().equals(PeerStatus.getOnlineState("").getState()))) {
                    m_lastDirectConnectionWasSucessful = Boolean.TRUE;
                    m_unreachableCounter = 0;
                }
            }
        } else if (key.equals(PeerNode.STATUS_REVERSE_DISCOVERED)) {
            m_reverseDiscovery = (Boolean) value;
        }

        if (informListeners) {
            informListeners();
        }
    }
}
